package com.mitac.mcd.cs.mobiletracking.socketserver;

import java.sql.PreparedStatement;
import java.util.Date;

import com.mitac.mcd.cs.mobiletracking.socketserver.util.BusinessUtil;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.DBConnection;
import com.mitac.mcd.cs.mobiletracking.socketserver.util.Formatter;

public class CheckOnlineCount extends Thread{
	
	MobileServer obj = null;
	private boolean _run = true;
	
	public CheckOnlineCount(MobileServer mobileServerObj){
		this.obj = mobileServerObj;
		this.start();
	}
	
	public void stopThread() {
        this._run = false;
    }
	
	public void run() {
		BusinessUtil.aLogger.info("新开CheckOnlineCount线程...");
		while(_run){
			try {
				Thread.sleep(obj.onlineCountLogInterval*60*1000);
			} catch (InterruptedException e) {
				BusinessUtil.aLogger.info(obj.SERVER_SN+"对应的MobileServer线程sleep异常:"+e);
			}
			setOnlineCount(obj);
			if(obj.tcpSokcetMaxConnection*obj.onlineCountThreshold<=obj.outputStreams.size()){
				BusinessUtil.aLogger.error(obj.SERVER_SN+"在"+Formatter.db2_sdf.format(new Date())+"记录的在线client数量:"+obj.outputStreams.size()+
						",已经超过警戒值"+obj.tcpSokcetMaxConnection*obj.onlineCountThreshold);
			}else{
				BusinessUtil.aLogger.info(obj.SERVER_SN+"在"+Formatter.db2_sdf.format(new Date())+"记录的在线client数量:"+obj.outputStreams.size());
			}
		}
	}
	
	public static void setOnlineCount(MobileServer obj){
		if (obj==null){
			return;
		}
		java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
		String sqlA = " insert into ONLINE_USER_ANALYSIS " +
		"(ONLINE_COUNT,LOG_TIME,SOCKET_SERVER_IP,SOCKET_SERVER_PORT,NOTE) values " +
		"(?,?,?,?,?) ";
		try {
            dbc = DBConnection.getConnection("gpsdata");
			pst = dbc.prepareStatement(sqlA);
			Date date = new Date();
			pst.setInt(1, obj.outputStreams.size());
			pst.setTimestamp(2, new java.sql.Timestamp(date.getTime()));
			pst.setString(3,obj.IP);
			pst.setInt(4, obj.PORT);
			pst.setString(5, null);
			pst.executeUpdate();
			
			dbc.close();
            pst.close();
		} catch (Exception e) {
			BusinessUtil.aLogger.info("setOnlineClient:"+e);
		}
	}
}
